package com.alex.megacj;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Required;

import com.alex.megacj.handler.RequestContext;

public class StatsHandler {

	private File logFile;
	
	private DateFormat dateFormat;
	
	@Required
	public void setDateFormat(String dateFormat) {
		this.dateFormat = new SimpleDateFormat(dateFormat);
	}
	
	@Required
	public void setLogFile(File logFile) {
		this.logFile = logFile;
	}
	
	public void handleStats(RequestContext context) throws IOException {
		int in = 0;
		int clicks = 0;
		
		BufferedReader reader = null;
		try {
			Map<String, Integer> ipHits = new HashMap<String, Integer>();
			reader = new BufferedReader(new FileReader(logFile));
			String line;
			while ((line = reader.readLine()) != null) {
				String[] parts = StringUtils.split(line, "\t");
				String ip = parts[0];
//				Date date = dateFormat.parse(parts[1]);
				String ref = parts[3];
				if (ref.startsWith("Ref: ")) {
					ref = ref.substring(4);
				}
				
				URL refURL = null;
				try {
					refURL = new URL(ref);
				} catch (Exception e) {
					continue;
				}
				
				if (refURL.getHost().endsWith("." + context.mirrorHost)) {
					String targetHost = refURL.getHost().substring(0, refURL.getHost().length() - context.mirrorHost.length() - 1);
					if (context.scenario.isAllowedHost(targetHost)) {
						clicks++;
					} else {
						in++;
					}
				} else {
					in++;
				}
				
				Integer hits = ipHits.get(ip);
				if (hits == null) {
					ipHits.put(ip, 1);
				} else {
					ipHits.put(ip, hits + 1);
				}
			}
			
			context.response.getWriter().print("In: " + in + "<br />");
			context.response.getWriter().print("Clicks: " + clicks + "<br />");
			context.response.getWriter().print("Prod: " + clicks / in + "<br />");
			
		} finally {
			IOUtils.closeQuietly(reader);
		}
	}

}
